
import qs from 'qs';
import type { IHttpResponse } from '@/interface';
import { REACT_APP_REQUET_BASE_URL } from "@/constants"
export const fetchRequestPost = async<IHttpResponse>({ url = '', headers = {}, requestBody = {} }) => {
    const responsePromise = Promise.race([
        new Promise<IHttpResponse>((resolve, reject) => {
            try {
                const headerObject = new Headers()
                headerObject.append("content-type", "application/json")
                Object.assign(headerObject, headers)
                fetch(`${REACT_APP_REQUET_BASE_URL}${url}`, {
                    method: 'POST',
                    headers: headerObject,
                    body: JSON.stringify(requestBody)
                }).then((res) => res.json())
                    .then((result: IHttpResponse) => {
                        return resolve(result)
                    })
            } catch (error) {
                reject(error)
            }
        }),
        new Promise<IHttpResponse>((resolve, reject) => {
            setTimeout(() => {
                const response = {
                    code: '-1',
                    message: 'request time out',
                    data: {}
                } as any
                resolve(response);
            }, 10000);
        })
    ])
    return responsePromise
}

export const fetchRequestGet = async<IHttpResponse>({ url = '', headers = {}, data = {} }) => {
    const responsePromise = Promise.race([
        new Promise<IHttpResponse>((resolve, reject) => {
            try {
                const fetchGetUrl = `${REACT_APP_REQUET_BASE_URL}${url}${data ? `?${qs.stringify(data)}` : ''} `
                fetch(fetchGetUrl, {
                    method: 'GET',
                    //headers: Object.assign(new Headers(), headers),
                }).then((res) => res.json())
                    .then((result: IHttpResponse) => {
                        return resolve(result)
                    })
            } catch (error) {
                reject(error)
            }
        }),
        new Promise<IHttpResponse>((resolve, reject) => {
            setTimeout(() => {
                const response = {
                    code: '-1',
                    message: 'request time out',
                    data: {}
                } as any
                resolve(response);
            }, 10000);
        })
    ])
    return responsePromise
}